/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  socket_server_select.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(16/03/25)
 *         Author:  LingYun <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "16/03/25 14:44:15"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define ARRAY_SIZE(x)         (sizeof(x)/sizeof(x[0]))       //用整个数组的大小除第一个元素大小，得数组中元素个数

static inline void msleep(unsigned long ms);
static inline void print_usage(char *progname);
int socket_server_init(char *listen_ip, int listen_port);

int main(int argc, char **argv)
{
	int 				listenfd, connfd;
	int					serv_port = 0;
	int					daemon_run = 0;
	char			   *progname = NULL;
	int					opt;
	fd_set				rdset;
	int					rv;
	int					i, j;
	int					found;
	int					maxfd = 0;
	char				buf[1024];
	int					fds_array[1024];

	struct option		long_options[]=
	{
		{"daemon", no_argument, NULL, 'b'},
		{"port", required_argument, NULL, 'p'},
		{"help", no_argument, NULL, 'h'},
		{NULL, 0, NULL, 0}
	};

	progname = basename(argv[0]);

	while((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1)
	{
		switch(opt)
		{
			case 'b':
				daemon_run = 1;
				break;

			case 'p':
				serv_port = atoi(optarg);
				break;

			case 'h':
				print_usage(progname);
				return EXIT_SUCCESS;

			default:
				break;
		}
	}

	if(!serv_port)
	{
		print_usage(progname);
		return -1;
	}

	if((listenfd=socket_server_init(NULL, serv_port)) < 0)
	{
		printf("ERROR: %s server listen on port %d failure\n", argv[0], serv_port);
		return -2;
	}
	printf("%s server start to listen on port %d\n", argv[0], serv_port);

	if(daemon_run)         //是否要到后台运行
	{
		daemon(0, 0);      //到后台运行
	}

	for(i=0; i<ARRAY_SIZE(fds_array); i++)
	{
		fds_array[i] = -1;            //将数组中所有的文件描述符设为-1，即为空
	}
	fds_array[0] = listenfd;

	for( ; ; )
	{
		FD_ZERO(&rdset);              //将read数组清零
		for(i=0; i<ARRAY_SIZE(fds_array); i++)        //遍历完整个数组
		{
			if(fds_array[i] < 0)      //文件描述符不存在
				continue;
		        
	         maxfd = fds_array[i]>maxfd ? fds_array[i] : maxfd;
		     FD_SET(fds_array[i], &rdset);
		}

		rv = select(maxfd+1, &rdset, NULL, NULL, NULL);
		if(rv < 0)                    //失败
	 	{
			printf("select failure: %s\n", strerror(errno));
			break;
		}
		else if(rv == 0)              //超时
		{
			printf("select get timeout\n");
			continue;
		}

		if(FD_ISSET(listenfd, &rdset))                 //rv>0,判断是哪个文件描述符发生事件
		{
			if((connfd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0)       //第一类事件：有新的客户端连接
			{
				 printf("accept new client failure: %s\n", strerror(errno));
				 continue;
			}

			found = 0;
			for(i=0; i<ARRAY_SIZE(fds_array); i++)
			{
				if(fds_array[i] < 0)
				{
					printf("accept new client[%d] and add it into array\n", connfd);
                	fds_array[i] = connfd;
		        	found = 1;
		 			break;
		   		}
	 		}

			if(!found)            //没有找到空余位置存放connfd，数组内所有位置均被占用
			{
				printf("accept new client[%d] but full, so refuse it\n");
				close(connfd);
			}
		}
		else                //第二类事件：数组内的已连接客户端发送信息，需要read
		{
			for(i=0; i<ARRAY_SIZE(fds_array); i++)
			{
				if(fds_array[i]<0 || !FD_ISSET(fds_array[i], &rdset))    //排除掉不是发送信息的客户端
					continue;

				if((rv=read(fds_array[i], buf, sizeof(buf))) <= 0)
				{
					printf("socket[%d] read failure or get disconncet.\n", fds_array[i]);
					close(fds_array[i]);
					fds_array[i] = -1;          //读失败或连接断开，将数组内所占位置腾出来
				}
				else
				{
					printf("socket[%d] read get %d bytes data\n", fds_array[i], rv);

					for(j=0; j<rv; j++)
						buf[j]=toupper(buf[j]);

					if(write(fds_array[i] ,buf, rv) < 0)
					{
						printf("socket[%d] write failure: %s\n", fds_array[i], strerror(errno));
						close(fds_array[i]);
						fds_array[i] = -1;
					}
				}
			}
		}
	}

CleanUp:
	close(listenfd);
	return 0;
}


static inline void msleep(unsigned long ms)
{
	struct timeval		tv;

	tv.tv_sec = ms/1000;       		//秒
	tv.tv_usec = (ms%1000)*1000;    //微秒  

	select(0, NULL, NULL, NULL, &tv);
}


static inline void print_usage(char *progname)
{
	printf("Usage: %s [OPTION]...\n", progname);

	printf("%s is a socket server progname, which used to verify client and client and echo back string from it\n", progname);
	printf("\nMandatory arguments to long options are mandatory for short options too:\n");

	printf(" -b[daemon] set program running on background\n");
	printf(" -p[port] Socket server port address\n");
	printf(" -h[help] Display this help information\n");


	printf("\nExample: %s -b -p 8900\n", progname);
	return ;
}


int socket_server_init(char *listen_ip, int listen_port)
{
	struct sockaddr_in		servaddr;
	int						rv = 0;
	int						on = 1;
	int						listenfd;

	if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		printf("Use socket() to creat a TCP socket failure: %s\n", strerror(errno));
		return -1;
	}

	setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(listen_port);

	if(!listen_ip)       //没传ip
	{
		servaddr.sin_addr.s_addr = htonl(INADDR_ANY);          //监听所有ip
	}
	else
	{
		if(inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) <= 0)          //将ip转为4字节存入sin_addr
		{
			printf("inet_pton() set listen IP address failure.\n");
			rv = -1;
			goto CleanUp;
		}
	}

	if(bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
	{
		printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
		rv = -3;
		goto CleanUp;
	}

	if(listen(listenfd, 13) < 0)
	{
		printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
		rv = -4;
		goto CleanUp;
	}

CleanUp:
	if(rv < 0)
		close(listenfd);
	else
		rv = listenfd;

	return rv;
}

